Learn in 10 minutes

Learn in 10 minutes

Learn Lua in 10 minutes

Lua is a lightweight, high-level, multi-paradigm programming language designed primarily for embedded use in applications. It’s widely used in game development (like World of Warcraft and Roblox), embedded systems, and as a configuration language.

1. Writing Your First Lua Program

Let’s start with a simple program. Create a file named hello.lua and enter the following code:

print("Hello, World!")

Save the file and run the following command in the terminal or command line:

lua hello.lua

The output will be:

Hello, World!

This simple program demonstrates Lua’s basic output functionality. The print() function is used to display text information in the console.

2. Basic Syntax

Lua’s syntax is simple and clean. It uses a C-like syntax but is more lightweight and flexible.

-- This is a single-line comment
print("Hello, World!")

--[[
This is a multi-line comment
It can span multiple lines
]]

Basic syntax rules in Lua:

  • Comments: Single-line comments start with --, while multi-line comments use --[[ comment ]]
  • Statements: Typically one statement per line, semicolons ; are optional
  • Case Sensitivity: Lua is case-sensitive
  • Whitespace: Spaces and newlines are generally ignored

3. Variables and Data Types

Lua is dynamically typed, meaning you don’t need to declare variable types.

-- Variable assignment
name = "Lua"
age = 25
is_awesome = true
pi = 3.14159

-- Multiple assignment
x, y, z = 10, 20, 30

-- Nil value (represents no value)
empty = nil

print("Name:", name)
print("Age:", age)
print("Is awesome:", is_awesome)

Basic data types in Lua:

  • nil: Represents the absence of a value
  • boolean: true or false
  • number: Integer and floating-point numbers
  • string: Text data
  • table: The only data structure in Lua (arrays, dictionaries, objects)
  • function: First-class functions
  • userdata: C data types
  • thread: Coroutines

4. Strings and String Operations

-- String creation
str1 = "Hello"
str2 = 'World'
str3 = [[Multi-line
string]]

-- String concatenation
message = str1 .. " " .. str2
print(message)  -- Output: Hello World

-- String length
length = #"Hello"
print(length)   -- Output: 5

-- String methods
text = "hello world"
upper = text:upper()
lower = text:lower()
sub = text:sub(1, 5)

print(upper)    -- Output: HELLO WORLD
print(sub)      -- Output: hello

5. Tables (Arrays and Dictionaries)

Tables are Lua’s only data structure, serving as arrays, dictionaries, and objects.

-- Array-like table (indexed from 1)
fruits = {"apple", "banana", "cherry"}
print(fruits[1])  -- Output: apple
print(fruits[2])  -- Output: banana

-- Dictionary-like table
person = {
    name = "John",
    age = 30,
    city = "New York"
}
print(person.name)    -- Output: John
print(person["age"])  -- Output: 30

-- Mixed table
mixed = {
    "apple",
    "banana",
    color = "red",
    count = 5
}

-- Table operations
fruits = {"apple", "banana"}
table.insert(fruits, "cherry")  -- Add to end
table.insert(fruits, 2, "orange") -- Insert at position

print(table.concat(fruits, ", "))  -- Output: apple, orange, banana, cherry

6. Control Structures

-- If statements
age = 18

if age >= 18 then
    print("You are an adult")
elseif age >= 13 then
    print("You are a teenager")
else
    print("You are a child")
end

-- While loop
counter = 1
while counter <= 5 do
    print("Counter:", counter)
    counter = counter + 1
end

-- For loop (numeric)
for i = 1, 5 do
    print("Number:", i)
end

-- For loop (with step)
for i = 10, 1, -2 do
    print("Countdown:", i)
end

-- For loop (generic - iterating tables)
fruits = {"apple", "banana", "cherry"}
for index, fruit in ipairs(fruits) do
    print(index, fruit)
end

person = {name = "John", age = 30}
for key, value in pairs(person) do
    print(key, value)
end

7. Functions

-- Basic function
function greet(name)
    return "Hello, " .. name .. "!"
end

message = greet("Alice")
print(message)  -- Output: Hello, Alice!

-- Function with multiple return values
function calculate(a, b)
    return a + b, a - b, a * b, a / b
end

sum, diff, product, quotient = calculate(10, 5)
print("Sum:", sum)        -- Output: Sum: 15
print("Difference:", diff) -- Output: Difference: 5

-- Anonymous functions (lambdas)
multiply = function(x, y)
    return x * y
end

result = multiply(4, 5)
print(result)  -- Output: 20

-- Functions as first-class citizens
function apply_operation(x, y, operation)
    return operation(x, y)
end

result = apply_operation(6, 7, multiply)
print(result)  -- Output: 42

8. Modules and Require

Lua uses modules to organize code. Create a file called math_utils.lua:

-- math_utils.lua
local MathUtils = {}

function MathUtils.add(a, b)
    return a + b
end

function MathUtils.multiply(a, b)
    return a * b
end

return MathUtils

Then use it in another file:

-- main.lua
local math_utils = require("math_utils")

result = math_utils.add(10, 5)
print("Addition result:", result)  -- Output: Addition result: 15

result = math_utils.multiply(4, 6)
print("Multiplication result:", result)  -- Output: Multiplication result: 24

9. Error Handling

-- Basic error handling with pcall
function risky_operation()
    error("Something went wrong!")
end

-- Using pcall (protected call)
success, result = pcall(risky_operation)

if success then
    print("Operation succeeded:", result)
else
    print("Operation failed:", result)
end

-- Custom error messages
function divide(a, b)
    if b == 0 then
        error("Division by zero is not allowed")
    end
    return a / b
end

success, result = pcall(divide, 10, 0)
if not success then
    print("Error:", result)
end

10. Practical Examples

-- Simple calculator
function calculator()
    print("Simple Calculator")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    
    choice = tonumber(io.read())
    print("Enter first number:")
    num1 = tonumber(io.read())
    print("Enter second number:")
    num2 = tonumber(io.read())
    
    if choice == 1 then
        result = num1 + num2
        print("Result:", result)
    elseif choice == 2 then
        result = num1 - num2
        print("Result:", result)
    elseif choice == 3 then
        result = num1 * num2
        print("Result:", result)
    elseif choice == 4 then
        if num2 ~= 0 then
            result = num1 / num2
            print("Result:", result)
        else
            print("Error: Division by zero")
        end
    else
        print("Invalid choice")
    end
end

-- Run the calculator
-- calculator()

-- File operations
function read_file(filename)
    local file = io.open(filename, "r")
    if not file then
        return nil, "Cannot open file"
    end
    
    local content = file:read("*a")
    file:close()
    return content
end

content, err = read_file("example.txt")
if content then
    print("File content:", content)
else
    print("Error:", err)
end

Conclusion

Lua is a powerful yet simple language perfect for embedding in applications, game development, and scripting tasks. Its lightweight nature, flexible tables, and first-class functions make it an excellent choice for many programming scenarios.

Key advantages of Lua:

  • Lightweight: Small footprint, perfect for embedded systems
  • Fast: Just-in-time compilation with LuaJIT
  • Embeddable: Easy to integrate with C/C++ programs
  • Flexible: Dynamic typing and powerful table data structure
  • Portable: Runs on virtually any platform

To continue learning Lua, explore:

  • Lua standard library functions
  • Coroutines for concurrent programming
  • Metatables and metamethods for OOP
  • Lua C API for embedding
  • Popular frameworks like Love2D for game development

Happy coding with Lua!